const express = require('express')
// 创建 express 的服务器实例
const app = express()
const cors = require('cors')
const joi = require('joi')
const config = require('./config')
const expressJWT = require('express-jwt')
const http = require('http');
const socketIO = require('socket.io');
const server = http.createServer(app);
const io = socketIO(server,{
    cors: {
        origin: "http://localhost:8080",
    },
    // path:'/socket'
});
io.listen(3008);

const db = require('./db/index')

//用户
const userRouter = require('./router/user')
const userinfoRouter = require('./router/userinfo')
const uploadSingleImg=require('./router/uploadSingleImg')
const uploadMoreImg=require('./router/uploadMoreImg')
const publish=require('./router/publish')
const areas=require('./router/areas')
const uploadVideo=require('./router/uploadVideo')
const article=require('./router/article')
const contacts=require('./router/contacts')
const chat=require('./router/chat')


app.use(express.json());
app.use(express.urlencoded({ extended: false }))
app.use(cors())
app.use(express.static('public'))

// 响应数据的中间件
app.use(function (req, res, next) {
    // status = 0 为成功； status = 1 为失败； 默认将 status 的值设置为 1，方便处理失败的情况
    res.cc = function (err, status = 1) {
        res.send({
            // 状态
            status,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            message: err instanceof Error ? err.message : err,
        })
    }
    next()
})

// 错误中间件
app.use(function (err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(err)
    // 捕获身份认证失败的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败！')
    // 未知错误
    res.cc(err)
})

// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [ /^\/socket\.io\//,/^\/api\//] }))

app.use('/api', userRouter)
app.use('/my', userinfoRouter)
app.use(uploadSingleImg)
app.use(uploadMoreImg)
app.use(publish)
app.use(areas)
app.use(uploadVideo)
app.use(article)
app.use(contacts)
app.use(chat)

io.on('connection', (socket) => {
    console.log('New client connected');
  
    socket.on('message', (message) => {
      console.log('Message received:', message);
      //在chat表中新增记录
      const sql=`insert into chat (pub_id,pub_avatar,pub_name,receive_id,receive_avatar,receive_name,content,time) values (?,?,?,?,?,?,?,?)`
        db.query(sql, [message.pub_id,message.pub_avatar,message.pub_name,message.receive_id,message.receive_avatar,message.receive_name,message.content,message.time], (err, results) => {
            if(err){
                console.log('执行失败')
                return 
            }
            console.log('执行成功')
            return 
       })
       //别人发给自己需要更新内容，时间，未读数
      //在contacts表中更新未读消息
      const sql2=`update contacts set unRead = unRead+1,lastContent=?,lastTime=? where userId=? and peopleId = ? `
        db.query(sql2, [message.content,message.time,message.receive_id,message.pub_id], (err, results) => {
        if (err){
            console.log('执行失败2')
            return
        }
        console.log('执行成功2',results)
        return
    })
    //如果是自己发给别人，需要更新时间、内容，未读数不需要
    const sql3=`update contacts set lastContent=?,lastTime=? where userId=? and peopleId = ? `
        db.query(sql3, [message.content,message.time,message.pub_id,message.receive_id], (err, results) => {
        if (err){
            console.log('执行失败3')
            return
        }
        console.log('执行成功3',results)
        return
    })
      //这里要指定转发的用户，message里面要带发送的目的方
      io.emit('messageReceived', message);

    });
  
    socket.on('disconnect', () => {
      console.log('Client disconnected');
    });
});
// 调用 app.listen 方法，指定端口号并启动web服务器
app.listen(3007, function () {
    console.log('api server running at http://127.0.0.1:3007')
})